//
//  TJMeViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/3.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "TJMeViewController.h"
#import "MeatMeHeader.h"
#import "MeatMeSectionTableViewCell.h"
#import "MeatMeOrderTableViewCell.h"
#import "MeatMeServiceTableViewCell.h"
#import "MeatMeSurveyTableViewCell.h"

#import "SystemSetingViewController.h"
#import "LoginViewController.h"
#import "MessageViewController.h"
#import "SelectTagsViewController.h"
#import "AddressViewController.h"
#import "CommonQuestionsViewController.h"
#import "PrefectPersonalInfoViewController.h"
#import "ModifyPhotoViewController.h"
#import "DiscountCouponViewController.h"
#import "MyAdoptedViewController.h"
#import "MyAssetViewController.h"
#import "InviteFriendsViewController.h"



#import "MeHeaderView.h"
#import "OrderStatusView.h"
#import "PhotoAlbumView.h"
#import "MyServiceView.h"
#import "UIView+Add.h"

#import "TJNetWorking+Image.h"

#pragma mark - 调试VC
#import "SetUpPasswordViewController.h"
#import "PrefectPersonalInfoViewController.h"

@interface TJMeViewController ()

@property (nonatomic, strong) MeatMeHeader *header;
@property (nonatomic, strong) NSArray *icons;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *sectionTitles;


/**
 requestData
 */
@property (nonatomic , strong) NSMutableArray *requestDataArr;
/**
 UserDetailInfo
 */
@property (nonatomic , strong) UserDetailInfo *userDetailInfo;

/**
 isLogin
 */
@property (nonatomic , assign) BOOL isLogin;


@end

@implementation TJMeViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
    self.isLogin = userInfo.isLogin;
//    self.isLogin = YES;
    if (self.isLogin) {//登录状态
        self.header.type = MeatMeHeaderType_Login;
        [self requestHeaderData];
    }else {
        self.header.type = MeatMeHeaderType_None;
    }
}


- (void)setupUI
{
    
    self.sectionTitles = @[@"我的订单", @"", @"我的服务", @"干点儿活赚点儿钱", @""];
    self.icons = @[@"meat_me_ask", @"meat_me_question", @"meat_me_card", @"meat_me_quan"];
    self.titles = @[@"问卷调查", @"完善资料", @"身份认证", @"分享有礼"];

    [self.view addSubview:self.header];
}

//接口测试
- (void)test{
    
    TJNetWorking *manager = [TJNetWorking sharedInstance];
    [manager getMineVouchersListDatacallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {


    }];
    
//    [manager getMineCenterDatacallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//
//    }];
//    [manager getMeatListDatacallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//
//    }];
    
    
}

//上传图片接口请求
- (void)uploadPhotosWithPhotos {
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    @weakify(self);
    UIImage *image = [UIImage imageNamed:@"Information_headImage"];

    [[[PigMarketApi sharedInstance] uploadPhotosWithPhotosArr:@[image] account:account type:UpDateImageType_Photo]  subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        
        [photoList.imgList enumerateObjectsUsingBlock:^(Photos * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSLog(@"_____________   %@", obj.imgName);
        }];
        
        
//        if ([self.title isEqualToString:CommonPhotoTitle]) {//上传图片后 上传imgName接口请求
//            [self updatePhotosWithImgNameArr:photoList.imgList];
//        }else {//完善个人资料页照片   无需上传imgName接口请求
//            
//            //个人资料上传图片imageName
//            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationPhotosNameChanged object:self userInfo:@{@"photoNameModel":photoList.imgList}];
//            [self.navigationController popViewControllerAnimated:YES];
//        }
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


- (void)setupLayout
{
    self.tableView.mj_y = _header.bottom;
    self.tableView.height = KScreenHeight - _header.height - TJ_TabBarHeight;
}


//个人资料数据请求
- (void)requestHeaderData {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getUserDetailInfoWithMemberId:memberId] subscribeNext:^(UserDetailInfo * _Nullable userDetailInfo) {
        @strongify(self);
        self.header.item = userDetailInfo;
        self.userDetailInfo = userDetailInfo;
        
        //保存是否三方绑定标识
        
        UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
        userInfo.qqOpenid = userDetailInfo.qqOpenid;
        userInfo.wbOpenid = userDetailInfo.wbOpenid;
        userInfo.wxOpenid = userDetailInfo.wxOpenid;
        userInfo.withdrawWx = userDetailInfo.withdrawWx;
        userInfo.memberName = userDetailInfo.memberName;//实名认证
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return 2;
    if (section == 1) return 1;
    if (section == 2) return 2;
    if (section == 3) return 5;
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return indexPath.row == 0 ?44 :85;
    }
    
    if (indexPath.section == 1) return 80;
    
    if (indexPath.section == 2)
    {
        return indexPath.row == 0 ?44 :251;
    }
    
    if (indexPath.section == 3)
    {
        return indexPath.row == 0 ?44 :75;
    }
   
    return 150;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = mBackgroudColor;
    return sectionView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 1 && indexPath.section !=4 &&indexPath.row == 0) {
        MeatMeSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeSectionTableViewCell"];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        }
        
        cell.titleLab.text = self.sectionTitles[indexPath.section];
        cell.detailLab.hidden = indexPath.section ==0 ?NO :YES;
        
        return cell;
    }
    
    if (indexPath.section == 0 && indexPath.row ==1) {
        
        MeatMeOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeOrderTableViewCell"];
        
        @weakify(self);
        //预支付
        cell.dealPayBlock = ^{
            @strongify(self);
            PrefectPersonalInfoViewController *personalInfoVC = [[PrefectPersonalInfoViewController alloc] init];
            personalInfoVC.title = PrefectPersonalInfoTitle;
            [self.navigationController pushViewController:personalInfoVC animated:YES];

        };
        
        //待收款
        cell.dealAcceptBlock = ^{
            
        };
        
        //待评价
        cell.dealEvaluationBlock = ^{
            
        };
        
        //售后
        cell.dealServiceBlock = ^{
            
        };
        
        return cell;
    }
    
    if (indexPath.section == 2 && indexPath.row ==1) {
        
        MeatMeServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeServiceTableViewCell"];
        
        @weakify(self);
        //我的收藏
        cell.dealCollectionBlock = ^{
            
        };
        
        //豚券
        cell.dealVouchersBlock = ^{
            
        };
        
        //我的资产
        cell.dealAssetsBlock = ^{
            @strongify(self);
            MyAssetViewController *vc = [[MyAssetViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //我的领养
        cell.dealAdoptBlock = ^{
            @strongify(self);
            MyAdoptedViewController *vc = [[MyAdoptedViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //购物车
        cell.dealCartBlock = ^{
            
        };

        //收货地址
        cell.dealLocationBlock = ^{
            
        };
        
        //常见问题
        cell.dealQuestionBlock = ^{
            
        };
        
        //帮助
        cell.dealHelpBlock = ^{
            
        };
        
        //我的肉铺
        cell.dealMeatShopBlock = ^{
            
        };
        
        return cell;
    }
    
    if (indexPath.section == 3) {
        
        MeatMeSurveyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeSurveyTableViewCell"];
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 15)];
        }
        
        cell.icon.image = [UIImage imageNamed:self.icons[indexPath.row -1]];
        cell.nameLab.text = self.titles[indexPath.row -1];
        
        return cell;
    }
    
    
    BaseIndentationTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseIndentationTableCell"];
    if (indexPath.section == 1 || indexPath.section == 4) {
        UIImage *image = [UIImage imageNamed:@"user_invitefriend"];
        cell.contentView.layer.contents = (__bridge id)image.CGImage;
    }
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - other methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat sectionHeaderHeight = 34;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark - getter and setter

- (void)registerTableViewCell
{
    self.tableView.separatorColor = mIconLineColor;
    
    [self.tableView registerClass:[BaseIndentationTableCell class] forCellReuseIdentifier:@"BaseIndentationTableCell"];
    [self.tableView registerClass:[MeatMeSectionTableViewCell class] forCellReuseIdentifier:@"MeatMeSectionTableViewCell"];
    [self.tableView registerClass:[MeatMeOrderTableViewCell class] forCellReuseIdentifier:@"MeatMeOrderTableViewCell"];
    [self.tableView registerClass:[MeatMeServiceTableViewCell class] forCellReuseIdentifier:@"MeatMeServiceTableViewCell"];
    [self.tableView registerClass:[MeatMeSurveyTableViewCell class] forCellReuseIdentifier:@"MeatMeSurveyTableViewCell"];
    
    UIView *footer = [UIView new];
    footer.backgroundColor = mBackgroudColor;
    footer.frame = CGRectMake(0, 0, KScreenWidth, 10);
    self.tableView.tableFooterView = footer;
    
}

- (MeatMeHeader *)header
{
    if (!_header) {
        _header = [[MeatMeHeader alloc] init];
        _header.type = MeatMeHeaderType_None;
        
        @weakify(self);
        //个人信息Block
        _header.dealUserInformationBlock = ^{
            @strongify(self);
            PrefectPersonalInfoViewController *modifyUserInfoVC = [[PrefectPersonalInfoViewController alloc] init];
            modifyUserInfoVC.title = ModifyPersonalInfoTitle;
            modifyUserInfoVC.userInfoModel = self.userDetailInfo;
            [self.navigationController pushViewController:modifyUserInfoVC animated:YES];
            
        };
        
        //消息Block
        _header.dealMessageBlock = ^{
            @strongify(self);
            
            CommonQuestionsViewController *vc = [[CommonQuestionsViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //设置Block
        _header.dealSetUpBlock = ^{
            @strongify(self);
            
            SystemSetingViewController *vc = [[SystemSetingViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        
        //登陆|注册
        _header.dealRegistLoginBlock = ^{
            @strongify(self);
            
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];

        };
        
        //申请服务商
        _header.dealServiceBlock = ^{
            @strongify(self);

            if (!self.isLogin) {
                PrefectPersonalInfoViewController *personalInfoVC = [[PrefectPersonalInfoViewController alloc] init];
                personalInfoVC.title = PrefectPersonalInfoTitle;
                [self.navigationController pushViewController:personalInfoVC animated:YES];
            }
        };
    }
    
    return _header;
}




#pragma mark - notifications

- (void)loginStatusChanged:(NSNotification *)notification {
    if ([UserInfoDataProvider sharedInstance].userInfo.isLogin) { // 登录成功
        self.header.type = MeatMeHeaderType_Login;
    }
}

- (void)addNotifications
{
    [kNotificationCenter addObserver:self selector:@selector(loginStatusChanged:) name:NotificationLoginStatusChanged object:nil];
}

- (void)removeNotifications
{
    [kNotificationCenter removeObserver:self name:NotificationLoginStatusChanged object:nil];
}

@end
